<?php

/**
 * Author: xx.com
 */

/**
 * lnshop检验登陆
 * @param
 * @return bool
 */
function is_login()
{
    if (isset($_SESSION['admin_id']) && $_SESSION['admin_id'] > 0) {
        return $_SESSION['admin_id'];
    } else {
        return false;
    }
}
function chk_telnumber($str){
	$REX ='/^(1(([356789][0-9])|[4][579]|[7][0135678]))\d{8}$/';
    if(!preg_match($REX,$str)||!is_numeric($str)||empty($str)) {
    	return FALSE;
    }else{
    	return TRUE;
    }
}
/**
 * 获取用户信息
 * @param $user_id_or_name  用户id 邮箱 手机 第三方id
 * @param int $type  类型 0 user_id查找 1 邮箱查找 2 手机查找 3 第三方唯一标识查找
 * @param string $oauth  第三方来源
 * @return mixed
 */
function get_user_info($user_id_or_name, $type = 0, $oauth = '')
{
    $map = array();
    if ($type == 0)
        $map['user_id'] = $user_id_or_name;
    if ($type == 1)
        $map['email'] = $user_id_or_name;
    if ($type == 2)
        $map['mobile'] = $user_id_or_name;
    if ($type == 3) {
        $map['openid'] = $user_id_or_name;
        $map['oauth'] = $oauth;
    }
    if ($type == 4) {
        $map['unionid'] = $user_id_or_name;
        $map['oauth'] = $oauth;
    }
    $user = M('users')->where($map)->find();
    return $user;
}

/**
 * 结算先到先得活动数据
 * @param $free_prizes_id 活动ID
 * @param $user_id 用户ID
 */
function settlement_free_prizes($free_prizes_id = 0,$user_id = 0){
	// 查询当前活动数据
	$where['start_time'] = ['ELT',time()];
	$where['settlement_users_id'] = 0;
	$where['is_on_sale'] = 1;
	$where['id'] = $free_prizes_id;
	$freePrizeInfo = M('free_prizes')->field('id,start_time,end_time,title,goods_id,integral,ratio,is_on_sale,content,settlement_time,settlement_users_id')->where($where)->find();
	if($freePrizeInfo){
		$freePrizesUsers = M('free_prizes_users')->where(['free_prizes_id'=>$freePrizeInfo['id'],'users_id'=>$user_id])->find();
		if($freePrizesUsers){
			// 修改活动数据
			M()->startTrans();
			// $save_free_prizes['id'] = $free_prizes_id;
			$save_free_prizes['settlement_users_id'] = $user_id;
			$save_free_prizes['settlement_time'] = time();
			$save_free_prizes_data = M('free_prizes')->where(['id'=>$free_prizes_id])->save($save_free_prizes);
			// p($save_free_prizes_data);die;
			if(!$save_free_prizes_data){
				M()->rollback();
				return array('is_success' => false, 'message' => '活动数据修改失败！','log_id' =>0);
			}
			// 创建相应代金券
			$coupon_data['send_start_time'] = time();
			$coupon_data['send_end_time'] = time()+1800;
			$coupon_data['use_end_time'] = time()+60*60*24*10;
			$coupon_data['use_start_time'] = time();
			$coupon_data['add_time'] = time();
			$coupon_data['name'] = '先到先得活动：'.$free_prizes_id.'商品券';
			$coupon_data['type'] = 5;
			$coupon_data['money'] = 0;
			$coupon_data['condition'] = 0;
			$coupon_data['createnum'] = 1;
			$coupon_data['send_num'] = 1;
			$coupon_data['use_num'] = 0;
			$coupon_row = M('coupon')->add($coupon_data);
			if(!$coupon_row){
				M()->rollback();
				return array('is_success' => false, 'message' => '商品券创建失败！','log_id' =>0);
			}
			// 发放代金券
			$add_coupon_list['cid'] = $coupon_row;
			$add_coupon_list['type'] = 5;
			$add_coupon_list['uid'] = $user_id;
			$add_coupon_list['order_id'] = 0;
			$add_coupon_list['goods_id'] = $freePrizeInfo['goods_id'];
			$add_coupon_list['use_time'] = 0;
			$add_coupon_list['send_time'] = time();
			$add_coupon_row = M('coupon_list')->add($add_coupon_list);
			if(!$add_coupon_row){
				M()->rollback();
				return array('is_success' => false, 'message' => '商品券发送失败！','log_id' =>0);
			}
			M()->commit();
			return array('is_success' => true, 'message' => '结算成功！','log_id' =>0);
		}else{
			return array('is_success' => false, 'message' => '此活动未参加！','log_id' =>0);
		}
	}else{
		return array('is_success' => false, 'message' => '无此活动！','log_id' =>0);
	}
	
}

/**
 * 查询现有三档排行
 */
function get_spell_top_list($spell_project_id){
    // 获取平均积分
    $where_avg_point['spell_project_id'] = $spell_project_id;
    $avg_point = M('spell_project_user')->where($where_avg_point)->avg('point');
    $last_point = M('spell_project_user')->where($where_avg_point)->order('point ASC')->find();
    $first_point = M('spell_project_user')->where($where_avg_point)->order('point DESC')->find();
    $last_point_count = 0;
    $first_point_count = 0;
    if($last_point){
        $last_point_count = $last_point['point'];
    }
    if($first_point){
        $first_point_count = $first_point['point'];
    }

    $one_point = $avg_point/50;
    $top_list = [
        ['name'=>'高分值区','limit'=>6,'screen_list'=>[$one_point*60,$first_point_count],'data'=>[]],
        ['name'=>'中分值区','limit'=>6,'screen_list'=>[$one_point*30,$one_point*60],'data'=>[]],
        ['name'=>'低分值区','limit'=>4,'screen_list'=>[$last_point_count,$one_point*30],'data'=>[]]
    ];
    // $top_list = [
    // 	['name'=>'高分值区','limit'=>6,'screen_list'=>[600,900],'data'=>[]],
    // 	['name'=>'中分值区','limit'=>6,'screen_list'=>[300,600],'data'=>[]],
    // 	['name'=>'低分值区','limit'=>4,'screen_list'=>[0,300],'data'=>[]]
    // ];
    // p($top_list);die;
    $not_in_user = '';
    foreach($top_list as $k=>&$v){
        // 查询当前档列表
        // p($v);
        $where_spell_top_list['point'] = ['BETWEEN',\implode(',',$v['screen_list'])];
        $where_spell_top_list['user_id'] = ['NOT IN',$not_in_user];
        $where_spell_top_list['spell_project_id'] = $spell_project_id;
        // $v['data'] = 1;
        $user_list = M('spell_project_user')->where($where_spell_top_list)->order('point DESC')->select();
        $v['data'] = $user_list;
        foreach($user_list as $ks => $vs){
            $not_in_user .= $vs['user_id'].",";
        }
    }

    return $top_list;
}

/**
 * 刷新先到先得活动数据
 * @param $free_prizes_id 活动ID
 * @param $user_id 用户ID
 */
function update_free_prizes($free_prizes_id = 0,$user_id = 0,$content = ''){
	// 查询当前活动数据
	$where['start_time'] = ['ELT',time()];
	$where['end_time'] = ['EGT',time()];
	$where['is_on_sale'] = 1;
	$where['id'] = $free_prizes_id;
	$freePrizeInfo = M('free_prizes')->field('id,start_time,end_time,title,goods_id,integral,ratio,is_on_sale,content,settlement_time,settlement_users_id')->where($where)->find();
	if($freePrizeInfo){
		$freePrizesUsers = M('free_prizes_users')->where(['free_prizes_id'=>$freePrizeInfo['id'],'users_id'=>$user_id])->find();
		
		if($freePrizesUsers){
			
			free_prizes_log($freePrizeInfo['id'], $user_id,$content);
			// 获取活动时间内的有效订单
			$where_all_order['user_id'] = $user_id;
			$where_all_order['pay_status'] = 1;
			$where_all_order['order_amount'] = ['GT',0];
			$where_all_order['pay_code'] = ['NEQ','money'];
			$where_all_order['pay_time'] = ['BETWEEN',[$freePrizesUsers['add_time'],$freePrizeInfo['end_time']]];
			$all_order_list = M('order')->where($where_all_order)->select();
			
			M('free_prizes_users_log')->where(['free_prizes_id'=>$freePrizeInfo['id'],'users_id'=>$user_id])->delete();
			$paymoney = 0;
			
			// 所有订单入库
			foreach($all_order_list as $k => $v){
				free_prizes_user_log($freePrizeInfo['id'], $user_id ,$v['order_id'],$v['order_amount'],0,$v['pay_time'],'订单支付'.$v['order_amount']);
				$paymoney += $v['order_amount'];
			}
			// 所有充值入库
			$where_all_recharge['user_id'] = $user_id;
			$where_all_recharge['pay_status'] = 1;
			$where_all_recharge['pay_time'] = ['BETWEEN',[$freePrizesUsers['add_time'],$freePrizeInfo['end_time']]];
			// p($where_all_recharge);die;
			$all_recharge_list = M('recharge')->where($where_all_recharge)->select();
			// p($all_recharge_list);die;
			foreach($all_recharge_list as $k => $v){
				free_prizes_user_log($freePrizeInfo['id'], $user_id ,$v['order_id'],$v['account'],0,$v['pay_time'],'余额充值'.$v['order_amount']);
				$paymoney += $v['account'];
			}
			// p($paymoney);die;
			// 更新参与记录信息
			$save_data['integral'] = intval($paymoney/$freePrizeInfo['ratio']);
			$save_data['all_pay_money'] = $paymoney;
			$save_data['last_update'] = time();
			$user_data = M('users')->where(['user_id'=>$user_id])->find();
			$save_data['nickname'] = $user_data['nickname'];
			M('free_prizes_users')->where(['id'=>$freePrizesUsers['id']])->save($save_data);
			return array('is_success' => true, 'message' => '刷新成功！','log_id' =>0);
		}else{
			return array('is_success' => false, 'message' => '此活动未参加！','log_id' =>0);
		}
	}else{
		return array('is_success' => false, 'message' => '无此活动！','log_id' =>0);
	}
	
}

/**
 * 更新会员等级,折扣，消费总额
 * @param $user_id  用户ID
 * @return boolean
 */
function update_user_level($user_id)
{
    $level_info = M('user_level')->order('level_id')->select();
    $where['user_id'] = $user_id;
    $where['pay_status'] = 1;
    $where['order_status'] = array('not in', '3,5');
    //用户实际支付金额
    $total_amount = M('order')->where($where)->sum('order_amount');
    //用户使用余额支付金额    注：原程序用户使用余额不用户计算用户等级，客户要求修改计入（2017/02/06） 代码修改：杜龙 ，客户负责人：王小策  2017/02/07修改
    $total_user_money = M('order')->where($where)->sum('user_money');
    //总金额 = 实际支付金额 + 余额支付金额
    $total_amount += $total_user_money;
    if ($level_info) {
        foreach ($level_info as $k => $v) {
            if ($total_amount >= $v['amount']) {
                $level = $level_info[$k]['level_id'];
                $discount = $level_info[$k]['discount'] / 100;
            }
        }
        $user = session('user');
        $updata['total_amount'] = $total_amount;//更新累计修复额度
    	//累计额度达到新等级，更新会员折扣
        if (isset($level) && $level > $user['level']) {
            $updata['level'] = $level;
            $updata['discount'] = $discount;
        }
        M('users')->where("user_id=$user_id")->save($updata);
    }
}

/**
 *  商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的
 * @param type $goods_id  商品id
 * @param type $width     生成缩略图的宽度
 * @param type $height    生成缩略图的高度
 */
function goods_thum_images($goods_id, $width, $height)
{

    if (empty($goods_id))
        return '';
    //判断缩略图是否存在
    $path = "Public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name = "goods_thumb_{$goods_id}_{$width}_{$height}";
  
    // 这个商品 已经生成过这个比例的图片就直接返回了
    if (file_exists($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg';
    if (file_exists($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg';
    if (file_exists($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif';
    if (file_exists($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png';

    $original_img = M('Goods')->where("goods_id = $goods_id")->getField('original_img');
    if (empty($original_img)) return '';

    $original_img = '.' . $original_img; // 相对路径
    if (!file_exists($original_img)) return '';

    $image = new \Think\Image();
    $image->open($original_img);

    $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
    //生成缩略图
    if (!is_dir($path))
        mkdir($path, 0777, true);
    
    //参考文章 http://www.mb5u.com/biancheng/php/php_84533.html  改动参考 http://www.thinkphp.cn/topic/13542.html
    $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, null, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
    
    //图片水印处理
    $water = tpCache('water');
    if ($water['is_mark'] == 1) {
        $imgresource = './' . $path . $goods_thumb_name;
        if ($width > $water['mark_width'] && $height > $water['mark_height']) {
            if ($water['mark_type'] == 'img') {
                $image->open($imgresource)->water("." . $water['mark_img'], $water['sel'], $water['mark_degree'])->save($imgresource);
            } else {
    		    //检查字体文件是否存在
                if (file_exists('./zhjt.ttf')) {
                    $image->open($imgresource)->text($water['mark_txt'], './zhjt.ttf', 20, '#000000', $water['sel'])->save($imgresource);
                }
            }
        }
    }
    return '/' . $path . $goods_thumb_name;
}

/**
 * 商品相册缩略图
 */
function get_sub_images($sub_img, $goods_id, $width, $height)
{
	//判断缩略图是否存在
    $path = "Public/upload/goods/thumb/$goods_id/";
    $goods_thumb_name = "goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}";
	//这个缩略图 已经生成过这个比例的图片就直接返回了
    if (file_exists($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg';
    if (file_exists($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg';
    if (file_exists($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif';
    if (file_exists($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png';

    $original_img = '.' . $sub_img['image_url']; //相对路径
    if (!file_exists($original_img)) return '';

    $image = new \Think\Image();
    $image->open($original_img);

    $goods_thumb_name = $goods_thumb_name . '.' . $image->type();
	// 生成缩略图
    if (!is_dir($path))
        mkdir($path, 777, true);
    $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, null, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存
    return '/' . $path . $goods_thumb_name;
}

/**
 * 刷新商品库存, 如果商品有设置规格库存, 则商品总库存 等于 所有规格库存相加
 * @param type $goods_id  商品id
 */
function refresh_stock($goods_id)
{
    $count = M("SpecGoodsPrice")->where("goods_id = $goods_id")->count();
    if ($count == 0) return false; // 没有使用规格方式 没必要更改总库存

    $store_count = M("SpecGoodsPrice")->where("goods_id = $goods_id")->sum('store_count');
    M("Goods")->where("goods_id = $goods_id")->save(array('store_count' => $store_count)); // 更新商品的总库存
}

/**
 * 根据 order_goods 表扣除商品库存
 * @param type $order_id  订单id
 */
function minus_stock($order_id)
{
    $orderGoodsArr = M('OrderGoods')->where("order_id = $order_id")->select();
    foreach ($orderGoodsArr as $key => $val) {
        // 有选择规格的商品
        if (!empty($val['spec_key'])) {   // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量
            M('SpecGoodsPrice')->where("goods_id = {$val['goods_id']} and `key` = '{$val['spec_key']}'")->setDec('store_count', $val['goods_num']);
            refresh_stock($val['goods_id']);
        } else {
            M('Goods')->where("goods_id = {$val['goods_id']}")->setDec('store_count', $val['goods_num']); // 直接扣除商品总数量
        }
        M('Goods')->where("goods_id = {$val['goods_id']}")->setInc('sales_sum', $val['goods_num']); // 增加商品销售量
        //更新活动商品购买量
        if ($val['prom_type'] == 1 || $val['prom_type'] == 2) {
            $prom = get_goods_promotion($val['goods_id']);
            if ($prom['is_end'] == 0) {
                $tb = $val['prom_type'] == 1 ? 'flash_sale' : 'group_buy';
                M($tb)->where("id=" . $val['prom_id'])->setInc('buy_num', $val['goods_num']);
                M($tb)->where("id=" . $val['prom_id'])->setInc('order_num');
            }
        }
    }
}

/**
 * 邮件发送
 * @param $to    接收人
 * @param string $subject   邮件标题
 * @param string $content   邮件内容(html模板渲染后的内容)
 * @throws Exception
 * @throws phpmailerException
 */
function send_email($to, $subject = '', $content = '')
{
    require_once THINK_PATH . 'Library/Vendor/phpmailer/PHPMailerAutoload.php';
    $mail = new PHPMailer;
    $config = tpCache('smtp');
    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 0;
    //调试输出格式
	//$mail->Debugoutput = 'html';
    //smtp服务器
    $mail->Host = $config['smtp_server'];
    //端口 - likely to be 25, 465 or 587
    $mail->Port = $config['smtp_port'];

    if ($mail->Port === 465) $mail->SMTPSecure = 'ssl';// 使用安全协议
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //用户名
    $mail->Username = $config['smtp_user'];
    //密码
    $mail->Password = $config['smtp_pwd'];
    //Set who the message is to be sent from
    $mail->setFrom($config['smtp_user']);
    //回复地址
    //$mail->addReplyTo('replyto@example.com', 'First Last');
    //接收邮件方
    if (is_array($to)) {
        foreach ($to as $v) {
            $mail->addAddress($v);
        }
    } else {
        $mail->addAddress($to);
    }

    $mail->isHTML(true);// send as HTML
    //标题
    $mail->Subject = $subject;
    //HTML内容转换
    $mail->msgHTML($content);
    //Replace the plain text body with one created manually
    //$mail->AltBody = 'This is a plain-text message body';
    //添加附件
    //$mail->addAttachment('images/phpmailer_mini.png');
    //send the message, check for errors
    return $mail->send();
}

/**
 * 发送短信
 * @param $mobile  手机号码
 * @param $content  内容
 * @return bool

function sendSMS($mobile,$content)
{
    $config = F('sms','',TEMP_PATH);
    $http = $config['sms_url'];			//短信接口
    $uid = $config['sms_user'];			//用户账号
    $pwd = $config['sms_pwd'];			//密码
    $mobileids = $mobile;         		//号码发送状态接收唯一编号
    $data = array
    (
        'uid'=>$uid,					//用户账号
        'pwd'=>md5($pwd.$uid),			//MD5位32密码,密码和用户名拼接字符
        'mobile'=>$mobile,				//号码，以英文逗号隔开
        'content'=>$content,			//内容
        'mobileids'=>$mobileids,
    );
    //即时发送
    $res = httpRequest($http,'POST',$data);//POST方式提交
    $stat = strpos($res,'stat=100');
    if($stat){
        return true;
    }else{
        return false;
    }
}
 */
//    /**
//     * 发送短信
//     * @param $mobile  手机号码
//     * @param $code    验证码
//     * @return bool    短信发送成功返回true失败返回false
//     */
function sendSMS($mobile, $code)
{
    //时区设置：亚洲/上海
    date_default_timezone_set('Asia/Shanghai');
    //这个是你下面实例化的类
    vendor('Alidayu.TopClient');
    //这个是topClient 里面需要实例化一个类所以我们也要加载 不然会报错
    vendor('Alidayu.ResultSet');
    //这个是成功后返回的信息文件
    vendor('Alidayu.RequestCheckUtil');
    //这个是错误信息返回的一个php文件
    vendor('Alidayu.TopLogger');
    //这个也是你下面示例的类
    vendor('Alidayu.AlibabaAliqinFcSmsNumSendRequest');

    $c = new \TopClient;
    $config = tpCache('sms');
    //短信内容：公司名/名牌名/产品名
    $product = $config['sms_product'];
    //App Key的值 这个在开发者控制台的应用管理点击你添加过的应用就有了
    $c->appkey = $config['sms_appkey'];
    //App Secret的值也是在哪里一起的 你点击查看就有了
    $c->secretKey = $config['sms_secretKey'];
    //这个是用户名记录那个用户操作
    $req = new \AlibabaAliqinFcSmsNumSendRequest;
    //代理人编号 可选
    $req->setExtend("123456");
    //短信类型 此处默认 不用修改
    $req->setSmsType("normal");
    //短信签名 必须
    $req->setSmsFreeSignName("注册验证");
    //短信模板 必须
    $req->setSmsParam("{\"code\":\"$code\",\"product\":\"$product\"}");
    //短信接收号码 支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，
    $req->setRecNum("$mobile");
    //短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。
    $req->setSmsTemplateCode($config['sms_templateCode']); // templateCode

    $c->format = 'json'; 
    //发送短信
    $resp = $c->execute($req);
    //短信发送成功返回True，失败返回false
    //if (!$resp)
    if ($resp && $resp->result)   // if($resp->result->success == true)
    {
        // 从数据库中查询是否有验证码
        $data = M('sms_log')->where("code = '$code' and add_time > " . (time() - 60 * 60))->find();
        // 没有就插入验证码,供验证用
        empty($data) && M('sms_log')->add(array('mobile' => $mobile, 'code' => $code, 'add_time' => time(), 'session_id' => SESSION_ID));
        return true;
    } else {
        return false;
    }
}

/**
 * 查询快递
 * @param $postcom  快递公司编码
 * @param $getNu  快递单号
 * @return array  物流跟踪信息数组
 */
function queryExpress($postcom, $getNu)
{
    $url = "http://wap.kuaidi100.com/wap_result.jsp?rand=" . time() . "&id={$postcom}&fromWeb=null&postid={$getNu}";
    //$resp = httpRequest($url,'GET');
    $resp = file_get_contents($url);
    if (empty($resp)) {
        return array('status' => 0, 'message' => '物流公司网络异常，请稍后查询');
    }
    preg_match_all('/\\<p\\>&middot;(.*)\\<\\/p\\>/U', $resp, $arr);
    if (!isset($arr[1])) {
        return array('status' => 0, 'message' => '查询失败，参数有误');
    } else {
        foreach ($arr[1] as $key => $value) {
            $a = array();
            $a = explode('<br /> ', $value);
            $data[$key]['time'] = $a[0];
            $data[$key]['context'] = $a[1];
        }
        return array('status' => 1, 'message' => 'ok', 'data' => array_reverse($data));
    }
}

/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson($cat_id)
{
    $GLOBALS['catGrandson'] = array();
    $GLOBALS['category_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['catGrandson'][] = $cat_id;
    // 把整张表找出来
    //$GLOBALS['category_id_arr'] = M('GoodsCategory')->cache(true,LNSHOP_CACHE_TIME)->getField('id,parent_id');
    $GLOBALS['category_id_arr'] = M('GoodsCategory')->getField('id,parent_id');
    // 先把所有儿子找出来
    //$son_id_arr = M('GoodsCategory')->where("parent_id = $cat_id")->cache(true,LNSHOP_CACHE_TIME)->getField('id',true);
    $son_id_arr = M('GoodsCategory')->where("parent_id = $cat_id")->getField('id', true);
    foreach ($son_id_arr as $k => $v) {
        getCatGrandson2($v);
    }
    return $GLOBALS['catGrandson'];
}

/**
 * 获取某个文章分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getArticleCatGrandson($cat_id)
{
    $GLOBALS['ArticleCatGrandson'] = array();
    $GLOBALS['cat_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['cat_id_arr'] = M('ArticleCat')->getField('cat_id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('ArticleCat')->where("parent_id = $cat_id")->getField('cat_id', true);
    foreach ($son_id_arr as $k => $v) {
        getArticleCatGrandson2($v);
    }
    return $GLOBALS['ArticleCatGrandson'];
}

/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id)
{
    $GLOBALS['catGrandson'][] = $cat_id;
    foreach ($GLOBALS['category_id_arr'] as $k => $v) {
        // 找到孙子
        if ($v == $cat_id) {
            getCatGrandson2($k); // 继续找孙子
        }
    }
}


/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getArticleCatGrandson2($cat_id)
{
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    foreach ($GLOBALS['cat_id_arr'] as $k => $v) {
        // 找到孙子
        if ($v == $cat_id) {
            getArticleCatGrandson2($k); // 继续找孙子
        }
    }
}

/**
 * 查看某个用户购物车中商品的数量
 * @param type $user_id
 * @param type $session_id
 * @return type 购买数量
 */
function cart_goods_num($user_id = 0, $session_id = '')
{
    $where = " session_id = '$session_id' ";
    $user_id && $where .= " or user_id = $user_id ";
    // 查找购物车数量
    $cart_count = M('Cart')->where($where)->sum('goods_num');
    $cart_count = $cart_count ? $cart_count : 0;
    return $cart_count;
}

/**
 * 获取商品库存
 * @param type $goods_id 商品id
 * @param type $key  库存 key
 */
function getGoodNum($goods_id, $key)
{
    if (!empty($key))
        return M("SpecGoodsPrice")->where("goods_id = $goods_id and `key` = '$key'")->getField('store_count');
    else
        return M("Goods")->where("goods_id = $goods_id")->getField('store_count');
}

/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache($config_key, $data = array())
{
    $param = explode('.', $config_key);
    if (empty($data)) {
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0], '', TEMP_PATH);//直接获取缓存文件
        if (empty($config)) {
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type='$param[0]'")->select();
            if ($res) {
                foreach ($res as $k => $val) {
                    $config[$val['name']] = $val['value'];
                }
                F($param[0], $config, TEMP_PATH);
            }
        }
        if (count($param) > 1) {
            return $config[$param[1]];
        } else {
            return $config;
        }
    } else {
        //更新缓存
        $result = D('config')->where("inc_type='$param[0]'")->select();
        if ($result) {
            foreach ($result as $val) {
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k => $v) {
                $newArr = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
                if (!isset($temp[$k])) {
                    M('config')->add($newArr);//新key数据插入数据库
                } else {
                    if ($v != $temp[$k])
                        M('config')->where("name='$k'")->save($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type='$param[0]'")->select();
            foreach ($newRes as $rs) {
                $newData[$rs['name']] = $rs['value'];
            }
        } else {
            foreach ($data as $k => $v) {
                $newArr[] = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
            }
            M('config')->addAll($newArr);
            $newData = $data;
        }
        return F($param[0], $newData, TEMP_PATH);
    }
}

/**
 * 订单关闭数据回归
 * @param string $order_sn     订单sn号码
 */
function cancelOrderRegression($order_sn = ''){
	// 查询订单信息
	$order = M('order')->where([
	    "order_sn" => $order_sn
	])->field("order_id,order_sn,user_id,shipping_price,order_amount,goods_price,user_money,integral_money,integral")->find();
	// p($order_sn);die;
	if($order){
		// p($order);die;
		// 回归积分信息
		$log = accountLog($order['user_id'], 0, $order['integral'], '数据回归' . $order_sn, 0, $order['order_id'], $order['order_sn']);
		return $log;
	}else{
		 return array('is_success' => false, 'message' => '回归失败！','log_id' =>0);
	}
}

/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $desc    变动说明
 * @param   float   distribut_money 分佣金额
 * @return  bool
 */
function accountLog($user_id, $user_money = 0, $pay_points = 0, $desc = '', $distribut_money = 0, $order_id = 0, $order_sn = '')
{
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id' => $user_id,
        'user_money' => $user_money,
        'pay_points' => $pay_points,
        'change_time' => time(),
        'order_id' => $order_id,
        'order_sn' => $order_sn,
        'desc' => $desc,
    );
    //获取用户信息
    $user_info = M('users')->field('user_money, pay_points')->where(array('user_id' => $user_id))->find();
    $update_user_money = $user_info['user_money'] + $user_money;
    $update_pay_points = $user_info['pay_points'] + $pay_points;

    if ($update_user_money > 99999999.99 || $update_user_money < -99999999.99 || $update_pay_points < 0 || $update_pay_points > 4294967295) {
        return array('is_success' => false, 'message' => '超出账户数据范围！','log_id' =>0);
    }

    /* 更新用户信息 */
    $sql = "UPDATE __PREFIX__users SET user_money = user_money + $user_money," .
        " pay_points = pay_points + $pay_points, distribut_money = distribut_money + $distribut_money WHERE user_id = $user_id";
    $update = D('users')->execute($sql);
    if ($update!==false) {
        $log_id = M('account_log')->add($account_log);
        if( $log_id )
            return array('is_success' => true, 'message' => '','log_id' => $log_id );
    }
    return array('is_success' => false, 'message' => '添加失败！','log_id' =>0);
}

/**
 * 订单操作日志
 * 参数示例
 * @param type $order_id  订单id
 * @param type $action_note 操作备注
 * @param type $status_desc 操作状态  提交订单, 付款成功, 取消, 等待收货, 完成
 * @param type $user_id  用户id 默认为管理员
 * @return boolean
 */
function logOrder($order_id, $action_note, $status_desc, $user_id = 0)
{
    $status_desc_arr = array('提交订单', '付款成功', '取消', '等待收货', '完成', '退货');
    // if(!in_array($status_desc, $status_desc_arr))
    // return false;

    $order = M('order')->where("order_id = $order_id")->find();
    $action_info = array(
        'order_id' => $order_id,
        'action_user' => $user_id,
        'order_status' => $order['order_status'],
        'shipping_status' => $order['shipping_status'],
        'pay_status' => $order['pay_status'],
        'action_note' => $action_note,
        'status_desc' => $status_desc, //''
        'log_time' => time(),
    );
    return M('order_action')->add($action_info);
}

/*
 * 获取地区列表
 */
function get_region_list()
{
    //获取地址列表 缓存读取
    if (!S('region_list')) {
        $region_list = M('region2')->select();
        $region_list = convert_arr_key($region_list, 'id');
        S('region_list', $region_list, 600);
    }

    return $region_list ? $region_list : S('region_list');
}
/*
 * 获取用户地址列表
 */
function get_user_address_list($user_id)
{
    $lists = M('user_address')->where(array('user_id' => $user_id))->select();
    return $lists;
}

/*
 * 获取指定地址信息
 */
function get_user_address_info($user_id, $address_id)
{
    $data = M('user_address')->where(array('user_id' => $user_id, 'address_id' => $address_id))->find();
    return $data;
}
/*
 * 获取用户默认收货地址
 */
function get_user_default_address($user_id)
{
    $data = M('user_address')->where(array('user_id' => $user_id, 'is_default' => 1))->find();
    return $data;
}
/**
 * 获取订单状态的 中文描述名称
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return string
 */
function orderStatusDesc($order_id = 0, $order = array())
{
    if (empty($order))
        $order = M('Order')->where("order_id = $order_id")->find();

    // 货到付款
    if ($order['pay_code'] == 'cod') {
        if (in_array($order['order_status'], array(0, 1)) && $order['shipping_status'] == 0)
            return 'WAITSEND'; //'待发货',
    } else // 非货到付款
    {
        if ($order['pay_status'] == 0 && in_array($order['order_status'], array(0, 1)))
            return 'WAITPAY'; //'待支付',
        if ($order['pay_status'] == 1 && in_array($order['order_status'], array(0, 1)) && $order['shipping_status'] != 1)
            return 'WAITSEND'; //'待发货',
    }
    if (($order['shipping_status'] == 1) && ($order['order_status'] == 1))
        return 'WAITRECEIVE'; //'待收货',
    if ($order['order_status'] == 2)
        return 'WAITCCOMMENT'; //'待评价',
    if ($order['order_status'] == 3)
        return 'CANCEL'; //'已取消',
    if ($order['order_status'] == 4)
        return 'FINISH'; //'已完成',
    if ($order['order_status'] == 5)
        return 'CANCELLED'; //'已作废',
    return 'OTHER';
}

/**
 * 获取订单状态的 显示按钮
 * @param type $order_id  订单id
 * @param type $order     订单数组
 * @return array()
 */
function orderBtn($order_id = 0, $order = array())
{
    if (empty($order))
        $order = M('Order')->where("order_id = $order_id")->find();
    /**
     *  订单用户端显示按钮
    去支付     AND pay_status=0 AND order_status=0 AND pay_code ! ="cod"
    取消按钮  AND pay_status=0 AND shipping_status=0 AND order_status=0
    确认收货  AND shipping_status=1 AND order_status=0
    评价      AND order_status=1
    查看物流  if(!empty(物流单号))
     */
    $btn_arr = array(
        'pay_btn' => 0, // 去支付按钮
        'cancel_btn' => 0, // 取消按钮
        'receive_btn' => 0, // 确认收货
        'comment_btn' => 0, // 评价按钮
        'shipping_btn' => 0, // 查看物流
        'return_btn' => 0, // 退货按钮 (联系客服)
        'drawback_btn' => 0, //退款按钮（新）
    );


    // 货到付款
    if ($order['pay_code'] == 'cod') {
        if (($order['order_status'] == 0 || $order['order_status'] == 1) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['cancel_btn'] = 1; // 取消按钮 (联系客服)
        }
        if ($order['shipping_status'] == 1 && $order['order_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
    }
    // 非货到付款
    else {
        if ($order['pay_status'] == 0 && $order['order_status'] == 0) // 待支付
        {
            $btn_arr['pay_btn'] = 1; // 去支付按钮
            $btn_arr['cancel_btn'] = 1; // 取消按钮
        }
        /*if($order['pay_status'] == 1 && in_array($order['order_status'],array(0,1)) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }*/
        if ($order['pay_status'] == 1 && $order['order_status'] == 1 && $order['shipping_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            //$btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
            //$btn_arr['drawback_btn'] = 1;       //退款按钮
        }
    }
    if ($order['order_status'] == 2) {
        //$btn_arr['comment_btn'] = 1;  // 评价按钮
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        //$btn_arr['drawback_btn'] = 1;       //退款按钮
    }
    if ($order['shipping_status'] != 0) {
        //$btn_arr['shipping_btn'] = 1; // 查看物流
    }
    if ($order['shipping_status'] == 2 && $order['order_status'] == 1) // 部分发货
    {
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        //$btn_arr['drawback_btn'] = 1;       //退款按钮
    }

    if ($order['order_status'] == 4) {
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        //$btn_arr['drawback_btn'] = 1;       //退款按钮
    }

    return $btn_arr;
}

/**
 * 给订单数组添加属性  包括按钮显示属性 和 订单状态显示属性
 * @param type $order
 */
function set_btn_order_status($order)
{
    $order_status_arr = C('ORDER_STATUS_DESC');
    $order['order_status_code'] = $order_status_code = orderStatusDesc(0, $order); // 订单状态显示给用户看的
    $order['order_status_desc'] = $order_status_arr[$order_status_code];
    $orderBtnArr = orderBtn(0, $order);
    return array_merge($order, $orderBtnArr); // 订单该显示的按钮
}


function doLog($message,$file="log")
{
    $file = C('LOG_PATH').$file."_".date('y_m_d').'.log'; 
    \Think\Log::write($message."\r\n","INFO",'',$file);
}


/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param $pay_code 支付方式 alipay、wxpay、pay_points、user_money
 * @param $pay_name 支付方式名称
 * @param $third_trade_no 第三方订单号
 * @param $trade_money 交易金额
 */
function update_pay_status($order_sn,$pay_code = '',$pay_name = '',$third_trade_no = '',$trade_money = 0)
{
    doLog($order_sn."-支付后订单处理-{.$pay_code}-{$third_trade_no}-{$trade_money}","payorder");
    if (stripos($order_sn, 'recharge') !== false) {
		//用户在线充值
        $count = M('recharge')->where("order_sn = '$order_sn' and pay_status = 0")->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
        if ($count == 0) return false;
        $order = M('recharge')->where("order_sn = '$order_sn'")->find();
        M('recharge')->where("order_sn = '$order_sn'")->save(array('pay_status' => 1, 'pay_time' => time()));
        accountLog($order['user_id'], $order['account'], 0, '会员在线充值');
    } else {
        // 如果这笔订单已经处理过了
        
        $count = M('order')->where("order_sn = '$order_sn' and pay_status = 0")->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
        if ($count == 0)
        {
            doLog($order_sn."无订单可处理","payorder");
            return true;
        } 
        doLog($order_sn."有订单可处理","payorder");
        // 找出对应的订单
        M()->startTrans();
        $order = M('order')->where("order_sn = '$order_sn'")->find();
        
        #理论上还要有金额验证

        // 修改支付状态  已支付
        $save = [
            "pay_status" => 1,
            'pay_time' => time(),
            'pay_code' => $pay_code,
            'pay_name' => $pay_name,
            'third_trade_no' => $third_trade_no,
        ];
        $is_auto_confirm = M('shop')->where(array('id'=>$order['shop_id']))->getField('is_auto_confirm');
        $save['order_status'] = $is_auto_confirm;

        $sql = M('order')->where("order_sn = '$order_sn'")->fetchSql(0)->save($save);
        
        if( !$sql )
        {
            M()->rollback();
            doLog($order_sn."订单处理失败".$sql,"payorder");
            return false;
        }
        // doLog($order_sn."订单处理成功","payorder");

        $order_id = $order['order_id']; //订单id

        #子订单全部为完成
        $child_orders = M("order")->where([
            "parent_sn" => $order_sn,
            "pay_status" => 0
        ])->count();

        if( $child_orders )
        {
            $child_orders_save = M("order")->where([
                "parent_sn" => $order_sn,
                "pay_status" => 0
            ])->save($save);

            if( $child_orders_save != $child_orders )
            {
                M()->rollback();
                doLog($order_sn."的子订单处理失败，数据回滚".$child_orders_save,"payorder");
                return false;
            }
        }

        // doLog($order_sn."订单信息-".json_encode($order)."--".$order['is_groupbuy'],"payorder");

        #处理团购商品
        if( $order['is_groupbuy'] == 1)
        {
            // doLog($order_sn."是团购订单--进行处理","payorder");
            $groupBuy = \Common\Logic\GroupbuyLogic::join( $order_sn );
            // doLog($order_sn."是团购订单--处理结果".json_encode($groupBuy),"payorder");
            if( $groupBuy['status']!=1 )
            {
                // M()->rollback();
                // return false;
                doLog($order_sn."团购订单处理失败-".json_encode($groupBuy),"payorder");
            }
        }

        #如果是现金支付的进入分销
        if( preg_match('/wx|wechat|weixin|zhifubao|alipay/i',$pay_code)  )
        {
            //分销开关全局
            $distribut_switch = tpCache('distribut.switch');
            if ($distribut_switch == 1 && file_exists(APP_PATH . 'Common/Logic/DistributLogic.class.php')) 
            {
                $distributLogic = new \Common\Logic\DistributLogic();
                $distributLogic->rebate_log($order,1); // 生成分成记录
            }

            //分销设置,在上面直接进行付款了
            // M('rebate_log')->where("order_id = {$order['order_id']}")->save(array('status' => 1));
        }       
      
		// 减少对应商品的库存
		// minus_stock($order['order_id']);
		// 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
		// update_user_level($order['user_id']);
		// 记录订单操作日志
        logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id']);
		
		// 成为分销商条件
        $distribut_condition = tpCache('distribut.condition');
        $userModel = M('users');
        if ($distribut_condition == 1)  // 购买商品付款才可以成为分销商
        $userModel->where("user_id = {$order['user_id']}")->save(array('is_distribut' => 1));
        // $user_info = $userModel->field('oauth, openid')->where(array('user_id' => $order['user_id']))->find();
        // if ($user_info['oauth'] == 'weixin') {
        //     $message = '你的订单 订单号:' . $order_sn . '付款成功, 请耐心等待卖家发货!';
        //     push_weixin_message($user_info['openid'], $message);
        // }
        \Common\Logic\MessageLogic::sendUserMsg([
            "user_id" => $order['user_id'],
            "type" => \Common\Logic\MessageLogic::ORDER_MSG,
            "title" => "订单通知",
            "content" => "你的订单 订单号:  {$order_sn} 付款成功, 请耐心等待卖家发货!",
            "ext" => [
                "order_sn" => $order_sn,
            ],
            "notice" => true
        ]);

        M()->commit();
        doLog($order_sn."支付订单处理成功","payorder");
        return $sql;
    }

}

/**
 * 订单确认收货
 * @param $id   订单id
 */
function confirm_order($id, $user_id = 0, $log = '')
{

    $where = "order_id = $id";
    $user_id && $where .= " and user_id = $user_id ";

    $order = M('order')->where($where)->find();
    if ($order['order_status'] != 1)
        return array('status' => -1, 'msg' => '该订单不能收货确认');

    $data['order_status'] = 2; // 已收货        
    $data['pay_status'] = 1; // 已付款        
    $data['confirm_time'] = time(); // 收货确认时间
    if ($order['pay_code'] == 'cod') {
        $data['pay_time'] = time();
    }
    $row = M('order')->where(array('order_id' => $id))->save($data);
    if (!$row)
        return array('status' => -3, 'msg' => '操作失败');

    order_give($order);// 调用送礼物方法, 给下单这个人赠送相应的礼物

    \Common\Logic\MessageLogic::sendUserMsg([
        "user_id" => $order['user_id'],
        "type" => \Common\Logic\MessageLogic::ORDER_MSG,
        "title" => "订单通知",
        "content" => "你的订单 订单号:  {$order['order_sn']} 已经确认收货!",
        "ext" => [
            "order_sn" => $order['order_sn'],
        ],
        "notice" => true
    ]);

    if( !empty($log) && is_string($log) )
    {
        order_log($order['order_sn'], '', $log, 2);
    }

        
        //分销设置

    M('rebate_log')->where("order_id = $id")->save(array('status' => 2, 'confirm' => time()));

    return array('status' => 1, 'msg' => '操作成功');
}

/**
 * 给订单送券送积分 送东西
 */
function order_give($order)
{
	//$order_goods = M('order_goods')->where("order_id=".$order['order_id'])->cache(true)->select();
    $order_goods = M('order_goods')->where("order_id=" . $order['order_id'])->select();
	//查找购买商品送优惠券活动
    foreach ($order_goods as $val) {
        if ($val['prom_type'] == 3) {
            $prom = M('prom_goods')->where('type=3 and id=' . $val['prom_id'])->find();
            if ($prom) {
                $coupon = M('coupon')->where("id=" . $prom['expression'])->find();//查找优惠券模板
                if ($coupon && $coupon['createnum'] > 0) {
                    $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                    if ($remain > 0) {
                        $data = array('cid' => $coupon['id'], 'type' => $coupon['type'], 'uid' => $order['user_id'], 'send_time' => time());
                        M('coupon_list')->add($data);
                        M('Coupon')->where("id = {$coupon['id']}")->setInc('send_num'); // 优惠券领取数量加一
                    }
                }
            }
        }
    }
	
	//查找订单满额送优惠券活动
    $pay_time = $order['pay_time'];
    $prom = M('prom_order')->where("type>1 and end_time>$pay_time and start_time<$pay_time and money<=" . $order['order_amount'])->order('money desc')->find();
    if ($prom) {
        if ($prom['type'] == 3) {
            $coupon = M('coupon')->where("id=" . $prom['expression'])->find();//查找优惠券模板
            if ($coupon) {
                if ($coupon['createnum'] > 0) {
                    $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                    if ($remain > 0) {
                        $data = array('cid' => $coupon['id'], 'type' => $coupon['type'], 'uid' => $order['user_id'], 'send_time' => time());
                        M('coupon_list')->add($data);
                        M('Coupon')->where("id = {$coupon['id']}")->setInc('send_num'); // 优惠券领取数量加一
                    }
                }
            }
        } else if ($prom['type'] == 2) {
            accountLog($order['user_id'], 0, $prom['expression'], "订单活动赠送积分");
        }
    }
    $points = M('order_goods')->where("order_id = {$order[order_id]}")->sum("give_integral * goods_num");
    $account_log_info = accountLog($order['user_id'], 0, $points, "下单赠送积分");
    $points && $account_log_info['is_success'];
}


/**
 * 查看商品是否有活动
 * @param goods_id 商品ID
 */

function get_goods_promotion($goods_id, $user_id = 0, $spec_price = 0)
{
    $now = time();
    $goods = M('goods')->where("goods_id=$goods_id")->find();
    //$user_id
    $where = "end_time>$now and start_time<$now and id=" . $goods['prom_id'];
    $goods_price = $spec_price ? $spec_price : $goods['shop_price'];        //带规格商品取商品模型对应规格价格 $spec_price ，无规格商品取goods['shop_price']
    $prom['price'] = $goods_price;
    $prom['prom_type'] = $goods['prom_type'];
    $prom['prom_id'] = $goods['prom_id'];
    $prom['is_end'] = 0;

    //$prom_price = 0;
    if ($goods['prom_type'] && $goods['prom_id']) {//优惠促销
        $parse_type = array('0' => '直接打折', '1' => '减价优惠', '2' => '固定金额出售', '3' => '买就赠优惠券', '4' => '买M件送N件');

        $prominfo = M('prom_goods')->where($where)->find(); //查询优惠活动
        $group_array = explode(',', $prominfo['group']);     //适用用户等级范围
        $level_name = '';

        //前台展示优惠范围
        if ($prominfo['group']) {
            $level_user_list = M('user_level')->where(array('level_id' => (array('in', $prominfo['group']))))->select();
        } else {
            $level_user_list = M('user_level')->select();
        }
        foreach ($level_user_list as $k => $level_user) {
            $level_name .= $level_user['level_name'] . ' ';
        }
        $prom['level_name'] = $level_name;

        $user = M('users')->where(array('user_id' => $user_id))->find();  //查询用户等级

        if (!empty($prominfo) && (in_array($user['level'], $group_array) || !$prominfo['group'])) {    //存在优惠，且适用于当前用户
            if ($prominfo['type'] == 0) {
                $prom['price'] = $prom['price'] * $prominfo['expression'] / 100;//打折优惠
            } elseif ($prominfo['type'] == 1) {
                $prom['price'] = $prom['price'] - $prominfo['expression'];//减价优惠
                $prom['price'] = $prom['price'] < 0 ? 0 : $prom['price'];
            } elseif ($prominfo['type'] == 2) {
                $prom['price'] = $prominfo['expression'];//固定金额优惠
            }
            $prom['goods_price'] = $prom['price'];
        } else {
            $user['discount'] = (empty($user['discount'])) ? 1 : $user['discount'];
            $prom['goods_price'] = intval($prom['price'] * 100) / 100;          // 购买价
            $prom['price'] = intval(round(($prom['price'] * $user['discount']), 2) * 100) / 100;
        }
    }
    //$prom_price = $goods_price - $prom['price'];
    //$prom['prom_price'] = $prom_price;
    if (!empty($prominfo)) {
        $prom['start_time'] = $prominfo['start_time'];
        $prom['end_time'] = $prominfo['end_time'];
        //查询优惠信息
        $promotion = M('prom_goods')->field('name')->where(array('id' => $goods['prom_id']))->find();
        $prom['name'] = $promotion['name'];
    } else {
        $prom['prom_type'] = $prom['prom_id'] = 0;//活动已过期
        $prom['is_end'] = 1;//已结束
    }

    if ($prom['prom_id'] == 0) {
        M('goods')->where("goods_id=$goods_id")->save($prom);
    }
    return $prom;
}


//查看商品是否参与限时秒杀
function get_goods_kill($goods_id)
{
    $now = time();
    $goods = M('goods as g')->join('ln_flash_sale as fs on fs.goods_id=g.goods_id')->where("g.goods_id=$goods_id")->find();
    //$user_id
    // var_dump($goods);die;
    $where = "is_end=0 and id=" . $goods['prom_id'];
    $goods_price = $goods['price'];
    $prom['price'] = $goods_price;
    $prom['prom_type'] = $goods['prom_type'];
    $prom['prom_id'] = $goods['prom_id'];
    $prom['is_end'] = 0;
    if ($goods['prom_type'] && $goods['prom_id']) {//优惠促销
        $prominfo = M('flash_sale')->where($where)->find(); //查询优惠活动
        if (!empty($prominfo)) {
            $prom['goods_price'] = $prom['price'];
        } else {
            $prom['goods_price'] = intval($prom['price'] * 100) / 100;          // 购买价
        }
    }
    if ($prom['prom_id'] == 0) {
        M('goods')->where("goods_id=$goods_id")->save($prom);
    }
    return $prom;
}

//查看商品是否参与团购
function get_goods_group($goods_id)
{
    $now = time();
    $goods = M('goods as g')->join('ln_group_buy as pg on pg.id=g.prom_id')->where("g.goods_id=$goods_id and g.prom_type=2")->find();
    //$user_id
    $where['recommended'] = 1;
    $where['id'] = $goods['prom_id'];
    $goods_price = $goods['price'];
    $prom['price'] = $goods_price;
    $prom['prom_type'] = $goods['prom_type'];
    $prom['prom_id'] = $goods['prom_id'];
    $prom['recommended'] = 1;
    if ($goods['prom_type'] && $goods['prom_id']) {//优惠促销
        $prominfo = M('group_buy')->where($where)->find(); //查询优惠活动
        if (!empty($prominfo)) {
            $prom['goods_price'] = $goods_price;
        } else {
            $prom['goods_price'] = intval($prom['price'] * 100) / 100;          // 购买价
        }
    }
    if ($prom['prom_id'] == 0) {
        M('goods')->where("goods_id=$goods_id")->save($prom);
    }
    return $prom;

}


/**
 * 查看订单是否满足条件参加活动
 * @param order_amount 订单应付金额
 */
function get_order_promotion($order_amount, $user_id = 0, $pay_points = 0, $user_money = 0, $all_pay_point = 0, $shipping_price = 0)
{
    $order_amount -= $shipping_price;   //原始价格-运费 = 商品总价
    $parse_type = array('0' => '满额打折', '1' => '满额优惠金额', '2' => '满额送倍数积分', '3' => '满额送优惠券', '4' => '满额免运费');
    $now = time();
    $prom_list = M('prom_order')->where("type<2 and end_time>$now and start_time<$now and money<=$order_amount")->order('money desc')->select();   //查询优惠活动
    $level = M('users')->where(array('user_id' => $user_id))->getField('level');  //查询用户等级
    foreach ($prom_list as $key => $value) {
        if (!$value['group']) {                   //优惠活动无用户等级范围限制，取当前优惠活动，跳出循环
            $prom = $prom_list[$key];
            break;
        } else {
            $group_array = explode(',', $value['group']);    //优惠活动有用户等级范围限制，适用用户等级范围,string -> array
            if (in_array($level, $group_array)) {             //用户等级在范围内，取当前优惠活动，跳出循环
                $prom = $prom_list[$key];
                break;
            }
        }
    }
    $res = array('order_amount' => $order_amount, 'order_prom_id' => 0, 'order_prom_amount' => 0);
    
    //存在优惠，且适用于当前用户 优惠设置用户等级in_array($level, $group_array) 判断用户等级是否在数组中  未设置用户等级 $prom['group'] 为空
    if (!empty($prom)) {
        if ($prom['type'] == 0) {
            $res['order_amount'] = round($order_amount * $prom['expression'] / 100, 2);//满额打折
            $res['order_prom_amount'] = $order_amount - $res['order_amount'];
            $res['order_prom_id'] = $prom['id'];
        } elseif ($prom['type'] == 1) {
            $res['order_amount'] = $order_amount - $prom['expression'];//满额优惠金额
            $res['order_amount'] = $res['order_amount'] < 0 ? 0 : $res['order_amount'];
            $res['order_prom_amount'] = $prom['expression'];
            $res['order_prom_id'] = $prom['id'];
        }
    }
    $res['order_amount'] += $shipping_price;    //订单优惠后价格 + 运费 = 实际价格
    $order_amount_point = intval($res['order_amount'] * tpCache('shopping.point_rate'));   //商品总价最高可使用抵扣积分
    $all_pay_point = $all_pay_point > $order_amount_point ? $order_amount_point : $all_pay_point;   //商品允许使用总积分

    if ($pay_points > 0) {                                                                    //用户使用积分
        $pay_points = $pay_points > $all_pay_point ? $all_pay_point : $pay_points;
    } else {
        $pay_points = 0;
    }

    $res['integral_money'] = $pay_points;  //积分支付积分

    //$pay_points = ($res['integral_money'] / tpCache('shopping.point_rate')); // 积分支付 默认 100 积分等于 1块钱
    $res['order_amount'] = ($res['order_amount'] * 100 - $pay_points * 100) / 100; //  积分抵消应付金额

    $res['all_pay_point'] = $all_pay_point;     //订单最高可使用抵扣积分
    $user_money = $user_money > $res['order_amount'] ? $res['order_amount'] : $user_money;  // 余额支付
    $res['order_amount'] = ($res['order_amount'] * 100 - $user_money * 100) / 100; //  余额支付抵应付金额
    
    //$res['order_amount']  =  intval(round($res['order_amount'], 2) * 100) / 100;
	//$res['order_prom_amount'] = intval(round($res['order_prom_amount'], 2) * 100) / 100;
    $res['user_money'] = $user_money; //  余额支付抵应付金额
    //$res['user_money'] = intval(round($res['user_money'], 2) * 100) / 100;

    return $res;
}

/**
 * 计算商品的单，如果是活动的返回活动价（除了团购） 
 * 不对规格进行校验和处理
 * @param goodsInfo
 * @param spec_price 规格价
 * @param goods_spec 暂时没处理
 * @return [
        "price" => 10
        "is_prom" => bool
 * ]
 */ 
function calcGoodsPrice($goodsInfo = [], $spec_price = 0, $goods_spec=null)
{
    // 商品是活动商品
    if ($goodsInfo['prom_type'] && $goodsInfo['prom_id']) 
    {
        // $prominfo = M('prom_goods')->where(array('id' => $val['prom_id']))->find(); //查询优惠活动
        // $group_array = explode(',', $prominfo['group']);     //适用用户等级范围

        // $level = $user['level'];  //查询用户等级

        // if ($prominfo && (in_array($level, $group_array) || !$prominfo['group'])) {    //存在优惠，且适用于当前用户
        //     $order_prom_amount += (($val['prom_price'] * 100 - $val['member_goods_price'] * 100) / 100) * $val['goods_num'];
        //     $is_prom++;
        // }

        $now = time();

        if ($goodsInfo['prom_type'] == 1) {//限时抢购
            $prom = M('flash_sale')
                ->field('price')
                ->where([
                    "goods_id" => $goodsInfo['goods_id'],
                    "id"    =>  $goodsInfo['prom_id'],
                    "start_time" => ["lt",$now],
                    "end_time" => ["gt",$now],
                ])
                ->find();
        } elseif ($goodsInfo['prom_type'] == 2) 
        {   
            #团购的询价体系不在这里，仍然走单独购买
            $prom['price'] = $spec_price > 0 ? $spec_price : $goodsInfo['shop_price'];
        } else {
            //品牌清仓
            $where['goods_id'] = $goodsInfo['goods_id'];
            $where['id'] = $goodsInfo['prom_id'];
            $where['start_time'] = ["lt",$now];
            $where['end_time'] =["gt",$now];
            $qin = M("prom_goods as p")
                ->field('p.type,g.shop_price,p.expression')
                ->where($where)
                ->join('ln_goods as g on g.prom_id=p.id')
                ->find();
            if( $qin )
            {
                if ($qin['type'] == 0) {
                    $prom['price'] = bcmul($qin['shop_price'], $qin['expression'] /100 , 2 );//打折优惠
                } else {
                    // var_dump($qin['shop_price'],$qin['expression']);
                    $prom['price'] = bcsub($qin['shop_price'],$qin['expression'],2);//减价优惠
                }
            }            
        }
    }

    $res = [
        "price" => $spec_price > 0 ? $spec_price : $goodsInfo['shop_price'],
        "is_prom" => false
    ];

    if( isset($prom) && $prom )
    {
        $res = [
            "price" => $prom['price'],
            "is_prom" => true
        ];
    }

    return $res;
}

/**
 * 计算订单金额(只适用购物车里面商品)
 * @param type $user_id  用户id
 * @param type $order_goods  购买的商品 立即购买传goods_spec
 * @param type $shipping  物流code
 * @param type $shipping_price 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $province  省份
 * @param type $city 城市
 * @param type $district 县
 * @param type $pay_points 积分
 * @param type $user_money 余额
 * @param type $coupon_id  优惠券
 * @param type $couponCode  优惠码
 */

function calculate_price($is_buyNow = 0, $goods_id, $goods_num = 0, $user_id = 0, $order_goods = [], $shipping_price = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '', $province = 0, $city = 0, $district = 0)
{
    $cartLogic = new \Home\Logic\CartLogic();
    $user = M('users')->where("user_id = $user_id")->find();// 找出这个用户
    $goodsModel = M('goods');
    $all_exchange_integral = 0;// 兑换积分
    $is_prom = 0;   //是否存在优惠商品
    $anum = 0;//总购买数量
    $goods_weight = 0;// 商品总重量
    $goods_price = 0;// 商品总价格
    $cut_fee = 0;//共节约
    $order_prom_amount = 0;

    #给新的计算邮费使用
    $shop_id = 0;
	$coupon_price = 0;
    if( !$is_buyNow )
    {
        if (empty($order_goods)) 
        { 
            return [
                'status' => -1, 
                'msg' => '购物车列表不能为空', 
                'result' => ''
            ];
        }
        $cartModel = M('cart');
        foreach ($order_goods as $key => &$val) 
        {
            $goodsInfo = $goodsModel->where([
                "goods_id" => $val['goods_id']
            ])->field('goods_id,weight,shop_id,shop_price,store_count,market_price,is_free_shipping,exchange_integral,prom_type,prom_id,is_on_sale')->find();
            
            if( !$goodsInfo || !$goodsInfo['is_on_sale'] )
            {
                $cartModel->where([
                    'id' => $val['id']
                ])->setField(array('status' => 0, 'selected' => 0));
                return [
                    'status' => -10, 
                    'msg' => '订单中存在失效商品，请重新下单！', 
                    'result' => ''
                ];
            }

            $shop_id = $goodsInfo['shop_id'];

            if (!empty($val['spec_key'])) // 有商品规格
            {
                $specGoodsPrice = M('SpecGoodsPrice')
                    ->field("key,key_name,price,store_count")
                    ->where(array('goods_id' => $goodsInfo['goods_id'], 'key' => $val['spec_key']))
                    ->find();       // 获取商品对应的规格价钱 库存

                $store_count = $specGoodsPrice['store_count']; //购买数量最大为库存
                $price = $specGoodsPrice['price']; // 获取规格指定的价格
            } else {
                $store_count = $goodsInfo['store_count']; //购买数量最大为库存
                $price = $goodsInfo['shop_price']; // 如果商品规格没有指定价格则用商品原始价格
            }

            if( $val['goods_num'] > $store_count )
            {
                $cartModel->where([
                    'id' => $val['id']
                ])->setField(array('status' => 0, 'selected' => 0));
                return [
                    'status' => -20, 
                    'msg' => '订单中商品:'.$goodsInfo['goods_name'].'库存不足，请重新下单！', 
                    'result' => ''
                ];
            }

            // 商品的单价
            $promPrice = calcGoodsPrice( $goodsInfo, $price,$val['spec_key'] );
            
            $price = $promPrice['price'];
            
            //如果商品不是包邮的
            if ($goodsInfo['is_free_shipping'] == 0)
            {
                $goods_weight += $goodsInfo['weight'] * $val['goods_num']; //累积商品重量 每种商品的重量 * 数量
            }

            // 商品价格小计
            $val['goods_fee'] = bcmul($val['goods_num'],$price,3);
            $val['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
            
            if ( $val['store_count'] <= 0 || $val['goods_num'] > $val['store_count'] )
            {
                return [
                    'status' => -1, 
                    'msg' => $val['goods_name'] . "库存不足,请重新下单", 
                    'result' => ''
                ];
            }
            // 商品总价
            $goods_price = bcadd($goods_price,$val['goods_fee'],2); 
            // 共节约
            $cut_fee_dirt = bcmul( $val['goods_num'], bcsub( $val['market_price'],  $price,2) ,2 );
            $cut_fee = bcadd($cut_fee, $cut_fee_dirt,2); 
            $anum += $val['goods_num']; // 购买数量
            // 兑换积分
            $all_exchange_integral = $all_exchange_integral + ($goodsInfo['exchange_integral'] * $val['goods_num']);
        }
    }else{
        #单一商品直接购买下单
        $goods_spec = $order_goods;
        $goods_arr = $goodsModel->where([
            "goods_id" => $goods_id
        ])->field('goods_id,weight,store_count,shop_id,shop_price,market_price,is_free_shipping,exchange_integral,prom_type,prom_id,is_on_sale')->find();
        if ( !$goods_arr || !$goods_arr['is_on_sale'] )
        {
            return [
                'status' => -10, 
                'msg' => '商品失效，请重新下单！'.$goods_id, 
                'result' => ''
            ];
        }

        

        if( empty($goods_spec) )
        {
            #判断是否有规格
            $spec = M('SpecGoodsPrice')
            ->where(['goods_id' => $goods_id])
            ->find();

            if( $spec )
            {
                return [
                    'status' => -10, 
                    'msg' => '请选择商品规格', 
                    'result' => ''
                ];
            }

            $store_count = $goods_arr['store_count']; //购买数量最大为库存
            $price = $goods_arr['shop_price']; // 如果商品规格没有指定价格则用商品原始价格
           
        }elseif (!empty($goods_spec)) // 有商品规格
        {
            $specGoodsPrice = M('SpecGoodsPrice')
                ->field("key,key_name,price,store_count")
                ->where(array('goods_id' => $goods_id, 'key' => $goods_spec))
                ->find();       // 获取商品对应的规格价钱 库存
            
            if( !$specGoodsPrice )
            {
                return [
                    'status' => -10, 
                    'msg' => '请选择正确的商品规格', 
                    'result' => ''
                ];
            }

            $store_count = $specGoodsPrice['store_count']; //购买数量最大为库存
            $price = $specGoodsPrice['price']; // 获取规格指定的价格
        }

        #$goods_num

        if( $goods_num > $store_count )
        {
            return [
                'status' => -10, 
                'msg' => '库存不足', 
                'result' => ''
            ];
        }

        // 商品的单价
        $promPrice = calcGoodsPrice( $goods_arr,$price, $goods_spec );            
        $price = $promPrice['price'];

        $shop_id = $goods_arr['shop_id'];

        // var_dump("goods_num",$goods_num);die;
        // var_dump("price",$price);die;

        //如果商品不是包邮的
        if ($goods_arr['is_free_shipping'] == 0) {
            $goods_weight = $goods_arr['weight'] * $goods_num; //累积商品重量 每种商品的重量 * 数量
        }
        // 商品总价 // 小计
        $goods_price = $goods_arr['goods_fee'] = bcmul($goods_num,$price,3);
        $cut_fee = bcmul( $goods_num, bcsub( $goods_arr['market_price'],  $price,2) ,2 );
        $anum = $goods_num; // 购买数量
        $all_exchange_integral =  $goods_arr['exchange_integral'] * $goods_num;
    }

    // 处理物流
    if ($shipping_price == 0) {
        // $freight_free = tpCache('shopping.freight_free'); // 全场满多少免运费
        // if ($freight_free > 0 && $goods_price >= $freight_free) {
        //     $shipping_price = 0;
        // } else {
        //     $shipping_price = $cartLogic->cart_freight2($goods_weight, $province, $city, $district);
        // }
        #使用了新的物流询价体系
        $shipping_price = \Common\Logic\FeeLogic::getPostFee($shop_id,$goods_weight,$goods_price);
    }

    // var_dump("goods_num",$goods_num);
    // var_dump("goods_weight",$goods_weight);
    // var_dump("goods_price",$goods_price);
    // var_dump("shipping_price",$shipping_price);
    // 应付金额 = 商品价格 + 物流费 - 优惠券
    $order_amount = bcadd( $goods_price , $shipping_price,2); 
    // $order_amount = ($goods_price+$shipping_price)-$pay_points;
    if ( bccomp($order_amount,0,2) < 1  )
    {
        $order_amount = 0;
    }

    $order_amount_uncharge = $order_amount;
    #积分兑换比例
    $point_rate = tpCache('shopping.point_rate');

    //判断该商品允许的最大积分 //商品总价最高可使用抵扣积分
    $order_amount_point = intval( $order_amount * $point_rate );
    $all_pay_point = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分
    
    if( $pay_points === true )
    {
        $pay_points = $all_pay_point;
    }

    if ($pay_points > 0) {
        if ($pay_points > $all_pay_point) {
            $pay_points = $all_pay_point;
        }
    } else {
        $pay_points = 0;
    }

    if ($pay_points > 0 && $pay_points > $user['pay_points']) 
    {
        return array('status' => -5, 'msg' => "积分余额不足，你的账户可用积分为:" . $user['pay_points'], 'result' => ''); // 返回结果状态                
    }

    $pay_points = ($pay_points / $point_rate ); // 积分支付 100 积分等于 1块钱 
    $pay_points = ($pay_points > $order_amount) ? $order_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
    $order_amount = bcsub( $order_amount, $pay_points,2 ); //  积分抵消应付金额
	// 查询优惠券信息
	if($coupon_id != 0 ){
		$Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
		$sql = "select c1.name,c1.money,c1.condition, c2.* from ln_coupon as c1 inner join ln_coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,5) and order_id = 0  where c2.id = {$coupon_id}  and c2.uid = {$user_id}  and " . time() . " < c1.use_end_time and c1.use_start_time < " . time();
		$couponList = $Model->query($sql);
		if(count($couponList) > 0){
			$couponData = $couponList[0];
			// 不同类型处理
			if($couponData['type'] == 5){// 商品全额抵扣
				$coupon_price = $order_amount;
				$order_amount = 0;
			}
		}
	}
    // $user_money = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
   // $order_amount = ($order_amount * 100 - $user_money * 100)/100; //  余额支付抵应付金额
    $total_amount = bcadd($goods_price,$shipping_price,2);
    // $total_amount = $goods_price+$shipping_price-$pay_points;
    $result = array(
        'total_amount' => $total_amount, // 订单总价
        'order_amount' => $order_amount, // 应付金额
        'shipping_price' => $shipping_price, // 物流费
        'goods_price' => $goods_price, // 商品总价
        'cut_fee' => $cut_fee, // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => $pay_points,  // 使用积分可以抵消金额
            // 'user_money'        => $user_money, // 使用余额
            'coupon_price'      => $coupon_price,// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表 多加几个字段原样返回
        'count_is_prom' => $is_prom,     //购买商品中存在优惠活动商品数量
            // 'order_prom_amount' => $order_prom_amount,  //订单优惠总金额
        'all_pay_point' => $all_pay_point,      //允许使用最大积分
        'available_points' => $user['pay_points'],//用户可用的积分
        'uncharge_amount' => $order_amount_uncharge,
    );
    return array('status' => 1, 'msg' => '计算成功', 'result' => $result);// 返回结果状态
}


/**
 * 计算订单金额
 * @param type $user_id  用户id
 * @param type $order_goods  购买的商品
 * @param type $shipping  物流code
 * @param type $shipping_price 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $province  省份
 * @param type $city 城市
 * @param type $district 县
 * @param type $pay_points 积分
 * @param type $user_money 余额
 * @param type $coupon_id  优惠券
 * @param type $couponCode  优惠码
 */

function calculate_price1($is_buyNow, $goods_id, $goods_num, $user_id = 0, $order_goods, $shipping_price = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '', $province = 0, $city = 0, $district = 0)
{
    $cartLogic = new \Home\Logic\CartLogic();
    $user = M('users')->where("user_id = $user_id")->find();// 找出这个用户
	$coupon_price = 0;
    if ($is_buyNow == 0) {
        if (empty($order_goods)) {
            return array('status' => -1, 'msg' => '购物车列表不能为空', 'result' => '');
        }

        $goods_id_arr = get_arr_column($order_goods, 'goods_id');
        $goods_arr = M('goods')->where("goods_id in(" . implode(',', $goods_id_arr) . ")")->getField('goods_id,weight,market_price,is_free_shipping,exchange_integral,prom_type,prom_id,is_on_sale'); // 商品id 和重量对应的键值对
        $all_exchange_integral = 0;
        $is_prom = 0;   //是否存在优惠商品
        $order_prom_amount = 0;
        foreach ($order_goods as $key => $val) {
            if (!$goods_arr[$val['goods_id']]['is_on_sale']) {
                M('cart')->where(array('id' => $val['id']))->setField(array('status' => 0, 'selected' => 0));
                return array('status' => -10, 'msg' => '订单中存在失效商品，请重新下单！', 'result' => '');
            }
            if ($val['prom_type'] && $val['prom_id']) {
                $prominfo = M('prom_goods')->where(array('id' => $val['prom_id']))->find(); //查询优惠活动
                $group_array = explode(',', $prominfo['group']);     //适用用户等级范围

                $level = M('users')->where(array('user_id' => $user_id))->getField('level');  //查询用户等级

                if ($prominfo && (in_array($level, $group_array) || !$prominfo['group'])) {    //存在优惠，且适用于当前用户
                    $order_prom_amount += (($val['prom_price'] * 100 - $val['member_goods_price'] * 100) / 100) * $val['goods_num'];
                    $is_prom++;
                }
            }
            // 如果传递过来的商品列表没有定义会员价
            if (!array_key_exists('member_goods_price', $val)) {
                $user['discount'] = $user['discount'] ? $user['discount'] : 1; // 会员折扣 不能为 0
                $order_goods[$key]['member_goods_price'] = $val['member_goods_price'] = ($val['goods_price'] * 100) * ($user['discount'] * 100) / 10000;
            }
            //如果商品不是包邮的
            if ($goods_arr[$val['goods_id']]['is_free_shipping'] == 0)
                $goods_weight += $goods_arr[$val['goods_id']]['weight'] * $val['goods_num']; //累积商品重量 每种商品的重量 * 数量

            $order_goods[$key]['goods_fee'] = $val['goods_num'] * ($val['member_goods_price'] * 100) / 100;    // 小计
            $order_goods[$key]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
            if ($order_goods[$key]['store_count'] <= 0)
                return array('status' => -1, 'msg' => $order_goods[$key]['goods_name'] . "库存不足,请重新下单", 'result' => '');

            $goods_price += $order_goods[$key]['goods_fee'] * 100; // 商品总价
            $cut_fee += ($val['goods_num'] * $val['market_price'] * 100 - $val['goods_num'] * $val['member_goods_price'] * 100) / 100; // 共节约
            $anum += $val['goods_num']; // 购买数量
            $all_exchange_integral = $all_exchange_integral + ($goods_arr[$val['goods_id']]['exchange_integral'] * $val['goods_num']);
        }
        $goods_price = $goods_price / 100;
        // 处理物流
        if ($shipping_price == 0) {
            $freight_free = tpCache('shopping.freight_free'); // 全场满多少免运费
            if ($freight_free > 0 && $goods_price >= $freight_free) {
                $shipping_price = 0;
            } else {
                $shipping_price = $cartLogic->cart_freight2($goods_weight, $province, $city, $district);
            }
        }
        if ($pay_points && ($pay_points > $user['pay_points'])) {
            return array('status' => -5, 'msg' => "你的账户可用积分为:" . $user['pay_points'], 'result' => ''); // 返回结果状态                
        }
        // if($user_money  && ($user_money > $user['user_money']))
        //     return array('status'=>-6,'msg'=>"你的账户可用余额为:".$user['user_money'],'result'=>''); // 返回结果状态
        $order_amount = ($goods_price * 100 + $shipping_price * 100) / 100; // 应付金额 = 商品价格 + 物流费 - 优惠券

        if ($order_amount < 0) {
            $order_amount = 0;
        }
        $order_amount_uncharge = $order_amount;
       //判断该商品允许的最大积分
        $order_amount_point = intval($order_amount * tpCache('shopping.point_rate'));   //商品总价最高可使用抵扣积分
        $all_pay_point = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分
        if ($pay_points > 0) {
            if ($pay_points > $all_pay_point) {
                $pay_points = $all_pay_point;
            }
        } else {
            $pay_points = 0;
        }


        $pay_points = ($pay_points / tpCache('shopping.point_rate')); // 积分支付 100 积分等于 1块钱 
        $pay_points = ($pay_points > $order_amount) ? $order_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
        $order_amount = ($order_amount * 100 - $pay_points * 100) / 100; //  积分抵消应付金额
       // $user_money = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
       // $order_amount = ($order_amount * 100 - $user_money * 100)/100; //  余额支付抵应付金额

        $total_amount = ($goods_price * 100 + $shipping_price * 100) / 100;

    } else {
        $goods_arr = M('goods')->field('goods_id,weight,shop_price,market_price,is_free_shipping,exchange_integral,prom_type,prom_id,is_on_sale')->where("goods_id=$goods_id")->find(); // 商品id 和重量对应的键值对
        $all_exchange_integral = 0;
        $is_prom = 0;   //是否存在优惠商品
        $order_prom_amount = 0;
        if ($goods_arr['is_on_sale'] == 0)
            $this->returnInfo('-1', '商品已失效，请重新选择');
        if ($goods_arr['prom_type'] && $goods_arr['prom_id']) {
            if ($goods_arr['prom_type'] == 1) {//限时抢购
                $kill = M('flash_sale')
                    ->field('price')
                    ->where("goods_id=$goods_id")
                    ->find();
                $price = $kill['price'];
            } elseif ($goods_arr['prom_type'] == 2) {//团购
                $group = M('group_buy')
                    ->field('price')
                    ->where("goods_id=$goods_id")
                    ->find();
                $price = $group['price'];
            } else {//品牌清仓
                $where['goods_id'] = $goods_id;
                $where['id'] = $goods_arr['prom_id'];
                $qin = M("prom_goods as p")
                    ->field('p.type,g.shop_price,p.expression')
                    ->where($where)
                    ->join('ln_goods as g on g.prom_id=p.id')
                    ->find();
                if ($qin['type'] == 0) {
                    $price = $qin['shop_price'] * $qin['expression'] / 100;//打折优惠
                } else {
                        // var_dump($qin['shop_price'],$qin['expression']);
                    $price = $qin['shop_price'] - $qin['expression'];//减价优惠
                    $price = strval($price) . '.00';
                }
            }
        } else {
            $price = $goods_arr['shop_price'];
        }

        //如果商品不是包邮的
        if ($goods_arr['is_free_shipping'] == 0) {
            $goods_weight += $goods_arr['weight'] * $goods_num; //累积商品重量 每种商品的重量 * 数量
        }
        $order_goods['goods_fee'] = ($goods_num * $price * 100) / 100;    // 小计
        $goods_price += $order_goods['goods_fee'] * 100; // 商品总价
        $order_goods['cut_fee'] += ($goods_num * $goods_arr['market_price'] * 100 - $goods_num * $price * 100) / 100; // 共节约
        $anum += $goods_num; // 购买数量
        $all_exchange_integral = $all_exchange_integral + ($goods_arr['exchange_integral'] * $goods_num);
        $goods_price = $goods_price / 100;
        // 处理物流
        if ($shipping_price == 0) {
            $freight_free = tpCache('shopping.freight_free'); // 全场满多少免运费
            if ($freight_free > 0 && $goods_price >= $freight_free) {
                $shipping_price = 0;
            } else {
                $shopping_price = 8;
                // $shipping_price = $cartLogic->cart_freight2($goods_weight, $province, $city, $district);
            }
        }
        if ($pay_points && ($pay_points > $user['pay_points'])) {
            return array('status' => -5, 'msg' => "你的账户可用积分为:" . $user['pay_points'], 'result' => ''); // 返回结果状态                
        }
        $order_amount = ($goods_price * 100 + $shipping_price * 100) / 100; // 应付金额 = 商品价格 + 物流费 - 优惠券

        if ($order_amount < 0) {
            $order_amount = 0;
        }
        $order_amount_uncharge = $order_amount;
       //判断该商品允许的最大积分
        $order_amount_point = intval($order_amount * tpCache('shopping.point_rate'));   //商品总价最高可使用抵扣积分
        $all_pay_point = $all_exchange_integral > $order_amount_point ? $order_amount_point : $all_exchange_integral;  //订单最高允许使用积分
        if ($pay_points > 0) {
            if ($pay_points > $all_pay_point) {
                $pay_points = $all_pay_point;
            }
        } else {
            $pay_points = 0;
        }

        $pay_points = ($pay_points / tpCache('shopping.point_rate')); // 积分支付 100 积分等于 1块钱 
       // $pay_points = ($pay_points > $order_amount) ? $order_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
        $order_amount = ($order_amount * 100 - $pay_points * 100) / 100;
		// 查询优惠券信息
		if($coupon_id != 0 ){
			$Model = new \Think\Model(); // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
			$sql = "select c1.name,c1.money,c1.condition, c2.* from ln_coupon as c1 inner join ln_coupon_list as c2  on c2.cid = c1.id and c1.type in(0,1,2,3,5) and order_id = 0  where c2.id = {$coupon_id}  and c2.uid = {$user_id}  and " . time() . " < c1.use_end_time and c1.use_start_time < " . time();
			$couponList = $Model->query($sql);
			if(count($couponList) > 0){
				$couponData = $couponList[0];
				// 不同类型处理
				if($couponData['type'] == 5){// 商品全额抵扣
					$coupon_price = $order_amount;
					$order_amount = ($order_amount * 100 - $coupon_price * 100) / 100;
				}
			}
		}

        $total_amount = ($goods_price * 100 + $shipping_price * 100) / 100;
    }
  
   
           //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
    $result = array(
        'total_amount' => $total_amount, // 商品总价
        'order_amount' => $order_amount, // 应付金额
        'shipping_price' => $shipping_price, // 物流费
        'goods_price' => $total_amount, // 商品总价
        'cut_fee' => $order_goods['cut_fee'], // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => $pay_points,  // 积分抵消金额
            // 'user_money'        => $user_money, // 使用余额
            'coupon_price'      => $coupon_price,// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表 多加几个字段原样返回
        'count_is_prom' => $is_prom,     //购买商品中存在优惠活动商品数量
            // 'order_prom_amount' => $order_prom_amount,  //订单优惠总金额
        'all_pay_point' => $all_pay_point,      //允许使用最大积分
        'uncharge_amount' => $order_amount_uncharge,
    );
    return array('status' => 1, 'msg' => '计算成功', 'result' => $result);// 返回结果状态
}

/**
 * 获取商品一二三级分类
 * @return type
 */
function get_goods_category_tree()
{
    $result = array();
	//$cat_list = M('goods_category')->where("is_show = 1")->order('sort_order')->cache(true)->select();//所有分类
    $cat_list = M('goods_category')->where("is_show = 1")->order('sort_order')->select();//所有分类

    foreach ($cat_list as $val) {
        if ($val['level'] == 2) {
            $arr[$val['parent_id']][] = $val;
        }
        if ($val['level'] == 3) {
            $crr[$val['parent_id']][] = $val;
        }
        if ($val['level'] == 1) {
            $tree[] = $val;
        }
    }

    foreach ($arr as $k => $v) {
        foreach ($v as $kk => $vv) {
            $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
        }
    }

    foreach ($tree as $val) {
        $val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
        $result[$val['id']] = $val;
    }
    return $result;
}

/**
 * 订单变更日志
 * @param $order_sn  订单编号
 * @param $log_user 操作人
 * @param $content 操作内容
 * @param $order_status 订单状态
 */
function order_log($order_sn, $log_user, $content, $order_status)
{
    $data = array();
    $data["order_sn"] = $order_sn;
    $data["log_user"] = $log_user;
    $data["content"] = $content;
    $data["add_time"] = time();
    $data["client_ip"] = get_client_ip();
    $data["order_status"] = $order_status;
    return M('order_log')->add($data);
}
/**
 * 先到先得用户资金日志
 * @param $free_prizes_id  活动id
 * @param $users_id 操作人
 * @param $order_id 数据订单号
 * @param $pay_money 支付金额
 * @param $type 数据类别
 * @param $content 操作内容
 */
function free_prizes_user_log($free_prizes_id, $users_id = 0,$order_id = 0,$pay_money = 0,$type = 0,$paytime = 0, $content = '')
{
    $data = array();
    $data["free_prizes_id"] = $free_prizes_id;
    $data["users_id"] = $users_id;
    $data["order_id"] = $order_id;
    $data["pay_money"] = $pay_money;
    $data["type"] = $type;
    $data["content"] = $content;
    $data["add_time"] = $paytime;
    $data["client_ip"] = get_client_ip();
    return M('free_prizes_users_log')->add($data);
}
/**
 * 先到先得日志
 * @param $free_prizes_id  活动id
 * @param $users_id 操作人
 * @param $content 操作内容
 */
function free_prizes_log($free_prizes_id, $users_id = 0, $content = '')
{
    $data = array();
    $data["free_prizes_id"] = $free_prizes_id;
    $data["users_id"] = $users_id;
    $data["content"] = $content;
    $data["add_time"] = time();
    $data["client_ip"] = get_client_ip();
    return M('free_prizes_log')->add($data);
}

 /**
 * 图片或者视频转成指定格式地址[支持一维数组]
 * @param str
 * @param str
 */ 
function parseMediaUrl($str = "")
{
    if(empty($str)|| $str == 'null')
    {
        return "";
    }

    if( is_array($str) )
    {
        foreach($str as &$v)
        {
            $v = parseMediaUrl($v);
        }
        return $str;
    }

    if( preg_match("/^http[s]?\:\/\//",$str) )
    {
        return $str;
    }

    $domain = CDN_URL ? CDN_URL : SITE_URL;
    if(  preg_match("/.*?[\.mp4|\.mov|\.flv|\.avi\.f4v]$/",$str) )
    {
        return $domain.$str;
    }
    //图片等其他类仍然使用域名
    return SITE_URL.$str;
}

/**
 * 处理商品详情的内容 
 * @param str string
 * @return string
 */ 
function parseRichTextContent($str = '')
{
    $str = htmlspecialchars_decode($str);
    // $str = str_replace('/Public/upload/', SITE_URL."/Public/upload/", $str);
    #正则取出图片或者视频的路径
    $REG = "/\<(img|embed)[^<>]*?\ssrc=[\'\"]?(.*?)[\'\"]?(\s.*?)?\>/";
    // $REG = "/\<[(img|embed)][^<>]*?\ssrc=[\'\"]?(.*?)[\'\"]?\s.*?\>/";
    $str = preg_replace_callback( $REG ,function($ma){
        if( $ma && $ma[1] && $ma[2] )
        {
            // return '<'.$ma[1].' src="'.parseMediaUrl($ma[2]).'" '.$ma[3].'>';
            return '<'.$ma[1].' src="'.parseMediaUrl($ma[2]).'">';
        }
    }, $str);

    $str = '<html><head><meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><style> .content img,.content embed{display:block;width:100%;height: auto;}embed{height:400px;}</style></head><body class="content">'.$str.'</body></html>';
    return $str;
}

/**
 * 商家订单状态
 * @param int $order_id
 * @param array $order
 * @return string
 */
function shopOrderStatusDesc($order_id = 0, $order = array())
{
    if (empty($order))
        $order = M('Order')->where("order_id = $order_id")->find();

    // 货到付款
    if ($order['pay_code'] == 'cod') {
        if ($order['order_status'] == 1 && $order['shipping_status'] == 0)
            return '待发货'; //'待发货',
    } else // 非货到付款
    {
        //待结单
        if($order['order_status'] == 0){
            return '待接单';
        }
        //待处理
        if($order['order_status'] == 1 && $order['shipping_status'] != 1 && $order['is_drawback'] == 0){
            return '待发货';
        }

        //已发货
        if($order['order_status'] == 1 && $order['shipping_status'] == 1 && $order['is_drawback'] == 0){
            return '已发货';
        }

        if(in_array($order['order_status'], array(2,4)) && $order['is_drawback'] == 1){
            return '待退款';
        }

        //已退款
        if($order['is_drawback'] == 2){
            return '已退款';
        }

        //'已取消',
        if ($order['order_status'] == 3)
            return '已取消';
        //'已完成',
        if (in_array($order['order_status'] ,array(2,4)) && $order['is_drawback'] == 0)
            return '已完成';

        if ($order['order_status'] == 5)
            return '已作废'; //'已作废',
    }
    return '其他';
}

function shopOrderBtn($order_id = 0, $order = array())
{
    if (empty($order))
        $order = M('Order')->where("order_id = $order_id")->find();

    $drawback_info = M('drawback')->where(array('order_id'=>$order['order_id']))->find();
    /**
     *  订单商家端显示按钮
     * 确认订单 order_status = 0
     *  发货 order_status = 1 AND shipping_status = 0
     * 确认退款  pay_status = 1 AND is_drawback = 1
     * 查看物流  shipping_status = 1 AND if(!empty(物流单号))
     */
    $btn_arr = array(
        'shipping_btn' => 0, // 查看物流
        'send_btn' => 0, //发货按钮
        'drawback_btn' => 0, //确认退款
        'confirm_btn' =>0, //接单按钮
        'allow_btn'=>0, //允许退款按钮
    );

    if ($order['order_status'] == 0 ) // 待发货
    {
        $btn_arr['confirm_btn'] = 1;
    }
    if ($order['order_status'] == 1 && $order['shipping_status'] == 0) // 待发货
    {
        $btn_arr['send_btn'] = 1;
    }

    /*if ($order['pay_status'] == 1 && $order['order_status'] == 1 && $order['is_drawback'] == 1) //待收货
        {
            $btn_arr['drawback_btn'] = 1;       //退款按钮
        }*/

    if ($order['shipping_status'] != 0) {
        $btn_arr['shipping_btn'] = 1; // 查看物流
    }

    if ($order['shipping_status'] == 2 && $order['order_status'] == 1) // 部分发货
    {
        $btn_arr['send_btn'] = 1;       //退款按钮
    }

    //if ($order['is_drawback'] == 1) {
    //    $btn_arr['drawback_btn'] = 1;       //退款按钮
    //}
    if($drawback_info){
        $btn_arr['allow_btn'] = $drawback_info['status'] == 0 ? 1 : 0;
        if($drawback_info['status'] == 3 || $drawback_info['status'] == 1 ){
            $btn_arr['drawback_btn'] = 1;
        }
    }

    return $btn_arr;
}

/**
 * 商家账户变动
 * @param $shop_id
 * @param int $user_money
 * @param string $desc
 * @param int $up_money_amount
 * @param int $service_fee
 * @param int $pay_points
 * @param int $order_id
 * @param string $order_sn
 * @return array
 */
function accountLogShop($shop_id, $user_money = 0, $desc = '', $up_money_amount = 0, $service_fee = 0, $pay_points = 0, $order_id = 0, $order_sn = '')
{
    /* 插入帐户变动记录 */
    $account_log = array(
        'shop_id' => $shop_id,
        'user_money' => $user_money,
        'pay_points' => $pay_points,
        'change_time' => time(),
        'order_id' => $order_id,
        'order_sn' => $order_sn,
        'desc' => $desc,
        'service_fee' => $service_fee
    );
    //获取用户信息
    $shop_info = M('shop')->field('wallet_balance, money_amount')->where(array('id' => $shop_id))->find();
    $update_wallet_balance = $shop_info['wallet_balance'] + $user_money;
    $up_money_amount_money = 0;
    if($up_money_amount == 1){
        $update_money_amount = $shop_info['money_amount'] + $user_money;
        $up_money_amount_money = $user_money;
    }

    if ($update_wallet_balance > 99999999.99 || $update_wallet_balance < -99999999.99 || $update_money_amount < 0 || $update_money_amount > 4294967295) {
        return array('is_success' => false, 'message' => '超出账户数据范围！','log_id' =>0);
    }

    /* 更新用户信息 */
    $sql = "UPDATE __PREFIX__shop SET wallet_balance = wallet_balance + $user_money," .
        " money_amount = money_amount + $up_money_amount_money WHERE id = $shop_id";
    $update = D('shop')->execute($sql);
    if ($update!==false) {
        $log_id = M('account_log_shop')->add($account_log);
        if( $log_id )
            return array('is_success' => true, 'message' => '','log_id' => $log_id );
    }
    return array('is_success' => false, 'message' => '添加失败！','log_id' =>0);
}

/**
 * 添加商户消息
 * @param $shop_id
 * @param string $title
 * @param string $message
 * @param int $type
 * @param int $rele_id
 * @param int $admin_id
 * @return array
 */
function add_shop_message($shop_id, $title = '', $message = '', $type = 0, $rele_id= 0, $admin_id= 0){
    $add_data['shop_id'] = $shop_id;
    $add_data['title'] = $title;
    $add_data['message'] = $message;
    $add_data['type'] = $type;
    $add_data['rele_id'] = $rele_id;
    $add_data['admin_id'] = $admin_id;
    $add_data['send_time'] = time();
    $id = M('message_shop')->add($add_data);
    if($id){
        return array('is_success' => true, 'message' => '添加成功！','message_id' =>$id);
    }
    return array('is_success' => false, 'message' => '添加失败！','message_id' =>0);
}

/**
 * 刷新新版先到先得活动数据
 * @param $free_prizes_id 活动ID
 * @param $user_id 用户ID
 */
function update_spell_project($spell_project_id = 0,$user_id = 0,$content = ''){
    // 查询当前活动数据
    $where['spell_project_id'] = $spell_project_id;
    $where['settlement_user_id'] = 0;
    $SpellProjectInfo = M('spell_project')->where($where)->find();

    if($SpellProjectInfo){
        $where_d['spell_project_id'] = $spell_project_id;
        $where_d['user_id'] = $user_id;
        $SpellProjectUsers = M('spell_project_user')->where($where_d)->find();
        // p($spell_project_id);
        if($SpellProjectUsers){
            // p($SpellProjectUsers);
            // 获取活动时间内的有效订单
            $where_all_order['user_id'] = $user_id;
            $where_all_order['pay_status'] = 1;
            $where_all_order['order_sn'] = ['LIKE','M%'];
            $where_all_order['order_amount'] = ['GT',0];
            $where_all_order['pay_time'] =['EGT',$SpellProjectInfo['wait_end_time']];

            $pay_time_str = "{$SpellProjectInfo['wait_end_time']},{$SpellProjectInfo['conduct_end_time']}";
            $where_all_order['pay_time'] = ['BETWEEN',$pay_time_str];
            $all_order_list = M('order')->where($where_all_order)->select();
            $spell_project_point_log['spell_project_id'] = $SpellProjectInfo['spell_project_id'];
            $spell_project_point_log['type'] = ['NEQ',2];
            $spell_project_point_log['users_id'] = $user_id;

            M('spell_project_point_log')->where($spell_project_point_log)->delete();
            $paymoney = 0;
            // p($all_order_list);die;
            // 所有订单入库
            foreach($all_order_list as $k => $v){
                if($v['total_amount'] >= 35){
                    $point = bcdiv($v['total_amount'],35,0)*10;
                    spell_project_user_log($SpellProjectInfo['spell_project_id'], $user_id ,$v['order_id'],$v['order_amount'],0,$v['pay_time'],$point,'订单大于35元。'.$v['order_amount']);

                    $paymoney += $v['order_amount'];
                }
                spell_project_user_log($SpellProjectInfo['spell_project_id'], $user_id ,$v['order_id'],0,0,$v['pay_time'],5,'每单赠送5积分');
            }
            // 所有充值入库
            $where_all_recharge['user_id'] = $user_id;
            $where_all_recharge['pay_status'] = 1;
            $where_all_recharge['pay_time'] = ['BETWEEN',[$SpellProjectInfo['wait_end_time'],$SpellProjectInfo['conduct_end_time']]];
            // p($where_all_recharge);die;
            $all_recharge_list = M('recharge')->where($where_all_recharge)->select();
            // p($all_recharge_list);die;
            foreach($all_recharge_list as $k => $v){
                $add_point = 0;
                if($v['account'] >= 100 && $v['account'] < 200){
                    $add_point = 30;
                }elseif($v['account'] < 300){
                    $add_point = 60;
                }elseif($v['account'] < 400){
                    $add_point = 90;
                }elseif($v['account'] < 500){
                    $add_point = 120;
                }elseif($v['account'] >= 500){
                    $add_point = 150;
                }
                if($add_point > 0){

                    spell_project_user_log($SpellProjectInfo['spell_project_id'], $user_id ,$v['order_id'],$v['account'],1,$v['pay_time'],$add_point,'余额充值'.$v['order_amount']);
                    $paymoney += $v['account'];
                }

            }
            // p($paymoney);die;
            // 更新参与记录信息
            $spell_project_point_logs = $spell_project_point_log;
            $spell_project_point_logs['type'] = 2;
            $save_data['point'] = M('spell_project_point_log')->where($spell_project_point_log)->sum('point')-M('spell_project_point_log')->where($spell_project_point_logs)->sum('point');
            $save_data['last_update'] = time();
            $user_data = M('users')->where(['user_id'=>$user_id])->find();
            $save_data['nickname'] = $user_data['nickname'];
            $save_data['id'] = $SpellProjectUsers['id'];
            M('spell_project_user')->save($save_data);

            return array('is_success' => true, 'message' => '刷新成功！','log_id' =>0);
        }else{
            return array('is_success' => false, 'message' => '此活动未参加！','log_id' =>0);
        }
    }else{
        return array('is_success' => false, 'message' => '无此活动！','log_id' =>0);
    }

}

